package com.doumuxie.service.impl;

import com.doumuxie.dto.UserDto;
import com.doumuxie.model.AuthRequest;
import com.doumuxie.service.AuthService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Service
public class AuthServiceImpl implements AuthService {


    @Override
    public UserDto auth(AuthRequest authRequest) {

        if (authRequest == null || StringUtils.isAnyBlank(
                authRequest.getUsername(),
                authRequest.getPassword()
        )) {
            throw new RuntimeException("用户名或密码为空");
        }

        UserDto result = findUserDto(authRequest.getUsername());
        if (result == null) {
            throw new RuntimeException("用户不存在");
        }
        if (!StringUtils.equals(result.getPassword(), authRequest.getPassword())) {
            throw new RuntimeException("用户名或密码错误");
        }

        //模拟从数据库查询权限数据
        if (StringUtils.equals(result.getId(), "000")) {
            // sadmin
            result.setAuth(AUTH_ALL);
        } else if (StringUtils.equals(result.getId(), "666")) {
            // admin
            result.setAuth(AUTH_R1);
        }

        return result;
    }

    private static UserDto findUserDto(String username) {
        return userDtoMap.get(username);
    }


    // 模拟用户
    private static Map<String, UserDto> userDtoMap = new HashMap<>();

    {
        userDtoMap.put("sadmin", new UserDto("000", "sadmin", "123123"));
        userDtoMap.put("admin", new UserDto("666", "admin", "123123"));
    }

    /**
     * 模拟权限数据
     */
    private static Set<String> AUTH_R1 = new HashSet<>();
    private static Set<String> AUTH_R2 = new HashSet<>();
    private static Set<String> AUTH_ALL = new HashSet<>();

    {
        AUTH_R1.add("/r1");
        AUTH_R2.add("/r2");
        AUTH_ALL.add("/r1");
        AUTH_ALL.add("/r2");
    }
}
